import api from '../utils/api';

// 用户类型定义
export interface User {
  id: number;
  username: string;
  password?: string;
  name: string;
  phone: string;
  email: string;
  role: number; // 1-管理员，2-老人，3-家属
  status: number; // 1-正常，0-禁用
  createTime: string;
  updateTime: string;
}

// 登录请求参数
export interface LoginRequest {
  username: string;
  password: string;
}

// 登录响应结果
export interface LoginResponse {
  token: string;
  user: User;
}

// 注册请求参数
export interface RegisterRequest {
  username: string;
  password: string;
  name: string;
  phone: string;
  email: string;
  role: number;
}

// 用户服务类
class UserService {
  // 登录
  async login(params: LoginRequest): Promise<LoginResponse> {
    return await api.post('/auth/login', params);
  }

  // 退出登录 - 简单实现为清除本地存储
  async logout(): Promise<void> {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    return Promise.resolve();
  }

  // 注册
  async register(params: RegisterRequest): Promise<User> {
    return await api.post('/auth/register', params);
  }

  // 获取用户信息
  async getUserInfo(): Promise<User> {
    return await api.get('/user/info');
  }

  // 更新用户信息
  async updateUserInfo(params: Partial<User>): Promise<User> {
    return await api.put('/user/info', params);
  }

  // 修改密码
  async changePassword(oldPassword: string, newPassword: string): Promise<void> {
    return await api.put('/user/password', { oldPassword, newPassword });
  }

  // 获取老人列表
  async getElderlyList(): Promise<User[]> {
    return await api.get('/user/elderly');
  }

  // 根据家属ID获取关联的老人列表
  async getElderlyByFamilyId(familyId: number): Promise<User[]> {
    return await api.get(`/user/elderly-by-family/${familyId}`);
  }
}

export default new UserService();